<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GoEmqxToDb 配置编辑器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 40px;
        }

        .section {
            margin-bottom: 40px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }

        .section-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
        }

        .section-content {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #4facfe;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .task-section {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            background: #fafafa;
        }

        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .task-title {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 172, 254, 0.3);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(255, 107, 107, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(86, 171, 47, 0.3);
        }

        .actions {
            text-align: center;
            margin-top: 40px;
            padding-top: 30px;
            border-top: 1px solid #e0e0e0;
        }

        .actions .btn {
            margin: 0 10px;
        }

        .json-view {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }

        .status {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .array-input {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 10px;
            background: white;
        }

        .array-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .array-item input {
            flex: 1;
            margin-right: 10px;
        }

        .array-item .btn {
            padding: 8px 12px;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔧 GoEmqxToDb 配置编辑器</h1>
            <p>编辑MQTT和数据库配置</p>
        </div>

        <div class="content">
            <div id="status" class="status"></div>

            <form id="configForm">
                <!-- MQTT配置 -->
                <div class="section">
                    <div class="section-header">
                        📡 MQTT 配置
                    </div>
                    <div class="section-content">
                        <div class="form-row">
                            <div class="form-group">
                                <label for="mqttHost">服务器地址</label>
                                <input type="text" id="mqttHost" name="mqttHost" placeholder="例如: localhost 或 192.168.1.100">
                            </div>
                            <div class="form-group">
                                <label for="mqttPort">端口</label>
                                <input type="number" id="mqttPort" name="mqttPort" value="1883" min="1" max="65535">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label for="mqttUsername">用户名</label>
                                <input type="text" id="mqttUsername" name="mqttUsername" placeholder="MQTT用户名">
                            </div>
                            <div class="form-group">
                                <label for="mqttPassword">密码</label>
                                <input type="password" id="mqttPassword" name="mqttPassword" placeholder="MQTT密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" id="mqttUserValidation" name="mqttUserValidation" checked>
                                启用用户验证
                            </label>
                        </div>
                    </div>
                </div>

                <!-- 任务配置 -->
                <div class="section">
                    <div class="section-header">
                        📋 任务配置
                    </div>
                    <div class="section-content">
                        <div id="tasksContainer">
                            <!-- 任务将通过JavaScript动态生成 -->
                        </div>
                        <button type="button" class="btn btn-success" onclick="addTask()">
                            ➕ 添加任务
                        </button>
                    </div>
                </div>

                <!-- JSON预览 -->
                <div class="section">
                    <div class="section-header">
                        📄 JSON 配置预览
                    </div>
                    <div class="section-content">
                        <div id="jsonPreview" class="json-view"></div>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="actions">
                    <button type="button" class="btn btn-primary" onclick="loadConfig()">
                        📂 加载配置
                    </button>
                    <button type="button" class="btn btn-success" onclick="saveConfig()">
                        💾 保存配置
                    </button>
                    <button type="button" class="btn btn-primary" onclick="resetConfig()">
                        🔄 重置为默认
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentConfig = null;
        let taskCounter = 0;

        // 默认配置
        const defaultConfig = [
            {
                "Version": "0.5.0",
                "MQTT": {
                    "serverType": 0,
                    "host": "localhost",
                    "port": 1883,
                    "userValidationEnabled": 1,
                    "username": "your_username",
                    "password": "your_password"
                },
                "Task": [
                    {
                        "taskNum": 1,
                        "taskName": "default_task",
                        "projectIdentifier": "your_project",
                        "projectKey": "your_project_key",
                        "qos": 0,
                        "remark": "",
                        "typeIndex": 0,
                        "type": "MySQL",
                        "database": "your_database",
                        "host": "localhost",
                        "port": 3306,
                        "username": "your_username",
                        "password": "your_password",
                        "storageType": 0,
                        "days": 0,
                        "hours": 1,
                        "groupIdentifier": ["default_group"],
                        "keyChannelIdentifier": ["", "", "", ""],
                        "remoteWritingEnabled": 1,
                        "commandTable": "_command",
                        "commandHistoryTable": "_command_history",
                        "pollingPeriod": 0.5
                    }
                ]
            }
        ];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadConfig();
        });

        // 加载配置
        async function loadConfig() {
            try {
                const response = await fetch('/api/config');
                if (response.ok) {
                    currentConfig = await response.json();
                    showStatus('配置加载成功', 'success');
                } else {
                    throw new Error('配置文件不存在或无法读取');
                }
            } catch (error) {
                console.log('使用默认配置:', error.message);
                currentConfig = JSON.parse(JSON.stringify(defaultConfig));
                showStatus('使用默认配置', 'success');
            }
            
            updateForm();
            updateJsonPreview();
        }

        // 保存配置
        async function saveConfig() {
            try {
                const config = getFormData();
                const response = await fetch('/api/config', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(config)
                });

                if (response.ok) {
                    showStatus('配置保存成功', 'success');
                    currentConfig = config;
                } else {
                    throw new Error('保存失败');
                }
            } catch (error) {
                showStatus('保存失败: ' + error.message, 'error');
            }
        }

        // 重置配置
        function resetConfig() {
            if (confirm('确定要重置为默认配置吗？')) {
                currentConfig = JSON.parse(JSON.stringify(defaultConfig));
                updateForm();
                updateJsonPreview();
                showStatus('已重置为默认配置', 'success');
            }
        }

        // 更新表单
        function updateForm() {
            if (!currentConfig || !currentConfig[0]) return;

            const config = currentConfig[0];
            const mqtt = config.MQTT;

            // 更新MQTT配置
            document.getElementById('mqttHost').value = mqtt.host || '';
            document.getElementById('mqttPort').value = mqtt.port || 1883;
            document.getElementById('mqttUsername').value = mqtt.username || '';
            document.getElementById('mqttPassword').value = mqtt.password || '';
            document.getElementById('mqttUserValidation').checked = mqtt.userValidationEnabled === 1;

            // 更新任务配置
            updateTasks(config.Task || []);
        }

        // 更新任务列表
        function updateTasks(tasks) {
            const container = document.getElementById('tasksContainer');
            container.innerHTML = '';
            taskCounter = 0;

            tasks.forEach((task, index) => {
                addTask(task);
            });
        }

        // 添加任务
        function addTask(taskData = null) {
            taskCounter++;
            const taskId = taskCounter;
            
            const task = taskData || {
                taskNum: taskId,
                taskName: `task_${taskId}`,
                projectIdentifier: "your_project",
                projectKey: "your_project_key",
                qos: 0,
                remark: "",
                typeIndex: 0,
                type: "MySQL",
                database: "your_database",
                host: "localhost",
                port: 3306,
                username: "your_username",
                password: "your_password",
                storageType: 0,
                days: 0,
                hours: 1,
                groupIdentifier: ["default_group"],
                keyChannelIdentifier: ["", "", "", ""],
                remoteWritingEnabled: 1,
                commandTable: "_command",
                commandHistoryTable: "_command_history",
                pollingPeriod: 0.5
            };

            const taskHtml = `
                <div class="task-section" id="task_${taskId}">
                    <div class="task-header">
                        <div class="task-title">任务 ${taskId}</div>
                        <button type="button" class="btn btn-danger" onclick="removeTask(${taskId})">
                            🗑️ 删除任务
                        </button>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label>任务名称</label>
                            <input type="text" name="taskName_${taskId}" value="${task.taskName}" placeholder="任务名称">
                        </div>
                        <div class="form-group">
                            <label>项目标识</label>
                            <input type="text" name="projectIdentifier_${taskId}" value="${task.projectIdentifier}" placeholder="项目标识">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>数据库主机</label>
                            <input type="text" name="dbHost_${taskId}" value="${task.host}" placeholder="数据库主机">
                        </div>
                        <div class="form-group">
                            <label>数据库端口</label>
                            <input type="number" name="dbPort_${taskId}" value="${task.port}" min="1" max="65535">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label>数据库名称</label>
                            <input type="text" name="database_${taskId}" value="${task.database}" placeholder="数据库名称">
                        </div>
                        <div class="form-group">
                            <label>数据库用户名</label>
                            <input type="text" name="dbUsername_${taskId}" value="${task.username}" placeholder="数据库用户名">
                        </div>
                    </div>

                    <div class="form-group">
                        <label>数据库密码</label>
                        <input type="password" name="dbPassword_${taskId}" value="${task.password}" placeholder="数据库密码">
                    </div>

                    <div class="form-group">
                        <label>组标识符</label>
                        <div class="array-input" id="groupIdentifier_${taskId}">
                            ${(task.groupIdentifier || []).map((item, index) => `
                                <div class="array-item">
                                    <input type="text" name="groupIdentifier_${taskId}_${index}" value="${item}" placeholder="组标识符">
                                    <button type="button" class="btn btn-danger" onclick="removeArrayItem('groupIdentifier_${taskId}', this)">删除</button>
                                </div>
                            `).join('')}
                            <button type="button" class="btn btn-success" onclick="addArrayItem('groupIdentifier_${taskId}')">添加组标识符</button>
                        </div>
                    </div>
                </div>
            `;

            document.getElementById('tasksContainer').insertAdjacentHTML('beforeend', taskHtml);
        }

        // 删除任务
        function removeTask(taskId) {
            if (confirm('确定要删除这个任务吗？')) {
                document.getElementById(`task_${taskId}`).remove();
                updateJsonPreview();
            }
        }

        // 添加数组项
        function addArrayItem(containerId) {
            const container = document.getElementById(containerId);
            const items = container.querySelectorAll('.array-item');
            const newIndex = items.length;
            const taskId = containerId.split('_')[1];
            
            const newItem = document.createElement('div');
            newItem.className = 'array-item';
            newItem.innerHTML = `
                <input type="text" name="${containerId}_${newIndex}" value="" placeholder="组标识符">
                <button type="button" class="btn btn-danger" onclick="removeArrayItem('${containerId}', this)">删除</button>
            `;
            
            container.insertBefore(newItem, container.lastElementChild);
        }

        // 删除数组项
        function removeArrayItem(containerId, button) {
            button.parentElement.remove();
        }

        // 获取表单数据
        function getFormData() {
            const config = JSON.parse(JSON.stringify(defaultConfig));
            const mqtt = config[0].MQTT;

            // 获取MQTT配置
            mqtt.host = document.getElementById('mqttHost').value;
            mqtt.port = parseInt(document.getElementById('mqttPort').value);
            mqtt.username = document.getElementById('mqttUsername').value;
            mqtt.password = document.getElementById('mqttPassword').value;
            mqtt.userValidationEnabled = document.getElementById('mqttUserValidation').checked ? 1 : 0;

            // 获取任务配置
            const tasks = [];
            const taskSections = document.querySelectorAll('.task-section');
            
            taskSections.forEach((section, index) => {
                const taskId = section.id.split('_')[1];
                const task = {
                    taskNum: index + 1,
                    taskName: document.querySelector(`[name="taskName_${taskId}"]`).value,
                    projectIdentifier: document.querySelector(`[name="projectIdentifier_${taskId}"]`).value,
                    projectKey: "your_project_key",
                    qos: 0,
                    remark: "",
                    typeIndex: 0,
                    type: "MySQL",
                    database: document.querySelector(`[name="database_${taskId}"]`).value,
                    host: document.querySelector(`[name="dbHost_${taskId}"]`).value,
                    port: parseInt(document.querySelector(`[name="dbPort_${taskId}"]`).value),
                    username: document.querySelector(`[name="dbUsername_${taskId}"]`).value,
                    password: document.querySelector(`[name="dbPassword_${taskId}"]`).value,
                    storageType: 0,
                    days: 0,
                    hours: 1,
                    groupIdentifier: [],
                    keyChannelIdentifier: ["", "", "", ""],
                    remoteWritingEnabled: 1,
                    commandTable: "_command",
                    commandHistoryTable: "_command_history",
                    pollingPeriod: 0.5
                };

                // 获取组标识符
                const groupInputs = document.querySelectorAll(`[name^="groupIdentifier_${taskId}_"]`);
                groupInputs.forEach(input => {
                    if (input.value.trim()) {
                        task.groupIdentifier.push(input.value.trim());
                    }
                });

                tasks.push(task);
            });

            config[0].Task = tasks;
            return config;
        }

        // 更新JSON预览
        function updateJsonPreview() {
            const config = getFormData();
            document.getElementById('jsonPreview').textContent = JSON.stringify(config, null, 2);
        }

        // 显示状态消息
        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = `status ${type}`;
            status.style.display = 'block';
            
            setTimeout(() => {
                status.style.display = 'none';
            }, 3000);
        }

        // 监听表单变化，实时更新JSON预览
        document.addEventListener('input', function() {
            updateJsonPreview();
        });
    </script>
</body>
</html> 